<?php
/*
 * @Author: KingMin 
 * @Date: 2021-07-13 22:35:31 
 * @Last Modified by:   KingMin 
 * @Last Modified time: 2021-07-13 22:35:31 
 * @The authors website: https://www.kingmin.cn  
 */
/**
 * 用户管理
 * @copyright (c) KINGMIN All Rights Reserved
 */

class User_Model {
    
    public static function getUserList($pages=[],$dt=[]){
        $DB=Database::getInstance();
        @$isAll=$pages['isAll'];
        $output = [
			'pages'=>[
			    'isAll'=>$isAll?true:false,
    			'recordCount' => 0,     //满足条件的总记录数
    		    'pageSize' => 10,        //每页大小，即每页最多可以显示的记录数量
    		    'pageCount' => 0,       //总页数
    		    'pno' => 1,          //当前数据所在页号
			 ],
			'list' => [] ,         //当前页中的数据
	    ];
	    $isfym="";$kSql="";$rSql="";$dSql="";
	    if(@$pages['pno']){
		  $output['pages']['pno'] = intval($pages['pno']);
		}
		if(@$pages['pageSize']){
		  $output['pages']['pageSize']= intval($pages['pageSize']);
		}
	    $pno = $output['pages']['pno'];$pgs =$output['pages']['pageSize'];
	    if(@$dt['name']&&@$dt['key']){
	        if($dt['name']=='uid'){
	            $kSql=" AND `uid`='".$dt['key']."' ";
	        }elseif($dt['name']=='uname'){
	            $kSql=" AND ( `uname` LIKE '%".$dt['key']."%' OR `nickName` LIKE '%".$dt['key']."%' OR `phone` LIKE '%".$dt['key']."%') ";
	        }else{
	            $kSql=" AND ( `".$dt['name']."` LIKE '%".$dt['key']."%' ) ";
	        }
	    }
	    if(@$dt['role']){
	        $rSql=" AND `role`='".$dt['role']."' ";
	    }
	    if(@$dt['isAdmin']){
	        $rSql=" AND `role`='ordinary' ";
	    }
	    if(@$dt['status']||@$dt['status']=='0'){
	        $dSql=" AND `status`='".$dt['status']."' ";
	    }
	    $totalSql = " SELECT COUNT(*) as total  FROM " . DB_PREFIX . "sys_member WHERE `isdel`='0' $kSql $rSql $dSql ;";
		$res = $DB->fetch_array($DB->query($totalSql));
		$output['pages']['recordCount'] = intval($res['total']);
		//计算总页数
		$output['pages']['pageCount'] = ceil($output['pages']['recordCount']/$output['pages']['pageSize']);
		//获取指定页中的数据
		$start = ($output['pages']['pno']-1)*$output['pages']['pageSize'];
		$count = $output['pages']['pageSize'];
		if(!$output['pages']['isAll']){
			$isfym="LIMIT $start,$count";
	    }
	    
	    $sql = "SELECT * FROM " . DB_PREFIX . "sys_member WHERE `isdel`='0' $kSql $rSql $dSql ORDER BY uid ASC  $isfym;";
        $logs = $DB->query($sql);
        // $output['sql']=$sql;
        $data = array();
        foreach ($logs as $key => $v) {
            // unset($v['user_password']);
            // $v['sql']=$sql;
            // $v['dt']=$dt;
            // $v['pges']=$pages;
            if($v['gender']==1){
                $sex='男';
            }elseif($v['gender']==2){
                $sex='女';
            }else{
                $sex='保密';
            }
            $v['sex'] = $sex;
            $v['avatar']=imgUrlpd($v['avatar']?htmlspecialchars($v['avatar']):'/content/images/icon/default.jpg');
            unset($v['password']);
            $data[]=$v;
        }
        $output['list']=$data;
        return $output;
    }
    
    // 获取角色列表
    public static function getRoleList($pages=[],$dt=[]){
        $DB=Database::getInstance();
        @$isAll=$pages['isAll'];
        $output = [
			'pages'=>[
			    'isAll'=>$isAll?true:false,
    			'recordCount' => 0,     //满足条件的总记录数
    		    'pageSize' => 10,        //每页大小，即每页最多可以显示的记录数量
    		    'pageCount' => 0,       //总页数
    		    'pno' => 1,          //当前数据所在页号
			 ],
			'list' => [] ,         //当前页中的数据
	    ];
	    $bySql="ORDER BY `order_num` ASC ";
	    $isfym="";$kSql="";$rSql="";$dSql="";
	    if(@$pages['pno']){
		  $output['pages']['pno'] = intval($pages['pno']);
		}
		if(@$pages['pageSize']){
		  $output['pages']['pageSize']= intval($pages['pageSize']);
		}
	    $pno = $output['pages']['pno'];$pgs =$output['pages']['pageSize'];
	    if(@$dt['name']&&@$dt['key']){
	       $kSql=" AND ( `".$dt['name']."` LIKE '%".$dt['key']."%' ) ";
	    }
	    if(@$dt['data_scope']){
	        $rSql=" AND `data_scope`='".$dt['data_scope']."' ";
	    }
	    if(@$dt['role_key']){
	        $rSql.=" AND `role_key`='".$dt['role_key']."' ";
	    }
	    if(@$dt['create_by']){
	        $rSql.=" AND `create_by`='".$dt['create_by']."' ";
	    }
	    if(@$dt['update_by']){
	        $rSql.=" AND `update_by`='".$dt['update_by']."' ";
	    }
	    if(@$dt['status']||@$dt['status']=='0'){
	        $dSql=" AND `status`='".$dt['status']."' ";
	    }
	    if(@$dt['orderBy']){
	        if($dt['orderBy']=="timeAsc"){
		        $bySql="ORDER BY `create_time` ASC ";
		    }
		    if($dt['orderBy']=="timeDesc"){
		        $bySql="ORDER BY `create_time` DESC ";
		    }
	    }
	    if(@$dt['orderBy']['order']){
	        if(strtolower($dt['orderBy']['order'])=='ascending'){
	            if(@$dt['orderBy']['prop']){
	               $bySql="ORDER BY `".$dt['orderBy']['prop']."` ASC "; 
	            }
	            
	        }
	        if(strtolower($dt['orderBy']['order'])=='descending'){
	            if(@$dt['orderBy']['prop']){
	               $bySql="ORDER BY `".$dt['orderBy']['prop']."` DESC "; 
	            }
	            
	        }
	    }
	    $totalSql = " SELECT COUNT(*) as total  FROM `" . DB_PREFIX . "sys_role` WHERE `isdel`='0' $kSql $rSql $dSql ;";
		$res = $DB->fetch_array($DB->query($totalSql));
		$output['pages']['recordCount'] = intval($res['total']);
		//计算总页数
		$output['pages']['pageCount'] = ceil($output['pages']['recordCount']/$output['pages']['pageSize']);
		//获取指定页中的数据
		$start = ($output['pages']['pno']-1)*$output['pages']['pageSize'];
		$count = $output['pages']['pageSize'];
		if(!$output['pages']['isAll']){
			$isfym="LIMIT $start,$count";
	    }
	    
	    $sql = "SELECT * FROM `" . DB_PREFIX . "sys_role` WHERE `isdel`='0' $kSql $rSql $dSql $bySql  $isfym;";
        $logs = $DB->query($sql);
        // $output['sql']=$sql;
        $data = array();
        foreach ($logs as $key => $v) {
            
            if($v['data_scope']=='1'){
                $tag=[
                    "type"=>"",
                    "label"=>"全部数据",
                ];
            }else{
                $tag=[
                    "type"=>"info",
                    "label"=>"仅自己",
                ];
            }
            $v['data_scopeTag']=$tag;
            
            if($v['status']=='0'){
                $tag=[
                    "type"=>"success",
                    "label"=>"正常",
                ];
            }else{
                $tag=[
                    "type"=>"danger",
                    "label"=>"停用",
                ];
            }
            $v['statusTag']=$tag;
            $createUser=[];
            if($v['create_by']){
                if($v['create_by']=='admin'){
                    $createUser=[
                        "uid"=>"admin",
                        "uname"=>"系统添加",
                    ];
                }else{
                    if($v['create_by']>0){
                        $createUser=self::getMemberDetail($v['create_by']); 
                    }
                }
            }
            $v['createUser']=$createUser;
            $updateUser=[];
            if($v['update_by']){
                if($v['update_by']=='admin'){
                    $updateUser=[
                        "uid"=>"admin",
                        "uname"=>"系统添加",
                    ];
                }else{
                    if($v['update_by']>0){
                        $updateUser=self::getMemberDetail($v['update_by']); 
                    }
                }
            }
            $v['updateUser']=$updateUser;
            $v['order_num']=intval($v['order_num']);
            $keys=self::getRoleMenuList($v['role_id']);
            
            $v['keys']=$keys['keys'];
            $v['node']=$keys['node'];
            $v['defaultKey']=$keys['defaultKey'];
            $data[]=$v;
        }
        $output['list']=$data;
        return $output;
    }
    
    // 获取角色菜单
    public static function getRoleMenuList($id){
        if(!$id){
            return [];
        }
        $DB=Database::getInstance();
        $menu=[];
        $sql="SELECT * FROM `".DB_PREFIX."sys_role_menu` where `role_id`='$id' ";
        $query=$DB->query($sql);
        while ($row = $DB->fetch_array($query)) {
            $mid=$row['menu_id'];
            $dt=self::getMenuDetail($mid);
            if($dt){
                if($dt['menu_type']=='F'){
                    $menu['defaultKey'][] = $mid??[];
                }else{
                    $menu['node'][] = $mid??[];
                }
                $menu['keys'][]=$mid??[];
            }
        }
        return $menu;
    }
    // 获取菜单详情
    public static function getMenuDetail($id){
        if(!$id){
            return false;
        }
        $DB=Database::getInstance();
        $menu=[];
        $sql="SELECT * FROM `".DB_PREFIX."sys_menu` where `menu_id`='$id' ";
        $query=$DB->query($sql);
        while ($row = $DB->fetch_array($query)) {
            $list=$row;
            $menu = $list??[];
        }
        return $menu;
    }
    // 获取菜单列表
    public static function getMenuList(){
        $DB=Database::getInstance();
        $menu=[];
        $sql="SELECT * FROM `".DB_PREFIX."sys_menu` where `parent_id`='0' AND `visible`='0' ORDER BY order_num ASC";
        $query=$DB->query($sql);
        while ($row = $DB->fetch_array($query)) {
            $mid=$row['menu_id'];
            $list=self::menuJson($row);
            $children=self::getChildren($mid);
            if($children){
                if($children['type']=="F"){
                    $list['isPenultimate']=true;
                }
                $list['children']=$children['list'];
            }
            $menu[] = $list??[];
        }
        return $menu;
    }
    
    // 菜单格式处理
    public static function menuJson($row){
        if(!is_array($row)){
            return false;
        }
        $id=$row['menu_id'];
        return  $naviData = array(
                    'id' => $id,
                    "label"=>$row["menu_title"]
                );
    }
    // 获取是否有子菜单
    public static function getChildren($id){
        if(empty($id)){
            return false;
        }
        $DB=Database::getInstance();
        $query=$DB->query("SELECT * FROM `".DB_PREFIX."sys_menu` where `parent_id`='$id'  AND `visible`='0' ORDER BY order_num ASC");
        $num=$DB->num_rows($query);
        if($num){
            $menu=[];$type="C";
            while ($row = $DB->fetch_array($query)) {
                $mid=$row['menu_id'];
                $type=$row['menu_type'];
                $list=self::menuJson($row);
                $children=self::getChildren($mid);
                if($children){
                    if($children['type']=="F"){
                        $list['isPenultimate']=true;
                    }
                    $list['children']=$children['list'];
                }
                $menu[] = $list??[];
            }
            return array("type"=>$type,"list"=>$menu);
        }else{
            return false;
        }
    }
    // 获取角色详情 id
    public static function getRoleDetail($id=""){
        if(!$id){
            return false;
        }
        $DB=Database::getInstance();
        
        $res = $DB->query("SELECT * FROM `".DB_PREFIX."sys_role` where `role_id`='$id' ");
        $role = array();
        while($row = $DB->fetch_array($res)) {
            $keys=self::getRoleMenuList($row['role_id']);
            
            $row['keys']=$keys['keys'];
            $role=$row;
        }
        return $role;
    }
    // 获取角色详情 key
    public static function getRoleDetailKey($key=""){
        if(!$key){
            return false;
        }
        $DB=Database::getInstance();
        
        $res = $DB->query("SELECT * FROM `".DB_PREFIX."sys_role` where `role_key`='$key' ");
        $role =false;
        while($row = $DB->fetch_array($res)) {
            $keys=self::getRoleMenuList($row['role_id']);
            
            $row['keys']=$keys['keys'];
            $role=$row;
        }
        return $role;
    }
    // 修改角色信息
    public static function uploadRoleDetail($roleData=[], $id=""){
        $DB=Database::getInstance();
        if(!$id){
            return false;
        }
        if(!is_array($roleData)){
            return false;
        }
        @$list=$roleData['keys'];
        if($list){
            unset($roleData['keys']);
            @$upm=self::uploadRoleMenu($list,$id);
            if(!$upm){
                return $upm;
            }
        }
        $rt=true;
        if(count($roleData)>0){
            $sql=upSqlConvert('sys_role',$roleData,"role_id=$id");
            $rt=$DB->query($sql);
            if(!$list){
                $CACHE = Cache::getInstance();
                $CACHE->updateCache('menus');
                $CACHE->updateCache('menuRole');
            }
        }
        return $rt;
    }
    // 新增角色信息
    public static function addRoleDetail($roleData=[]){
        $DB=Database::getInstance();
        $roleKey=self::getRoleDetailKey(@$roleData['role_key'])??true;
        if($roleKey){
            return false;
        }
        @$list=$roleData['keys'];
        // return $list;
        unset($roleData['keys']);
        $sql=addSqlConvert('sys_role',$roleData);
        // return $sql;
        $rt=true;
        $rt=$DB->query($sql);
        $id=$DB->insert_id();
        if($list){
            unset($roleData['keys']);
            @$upm=self::uploadRoleMenu($list,$id,true);
            if(!$upm){
                return $upm;
            }
        }
        return $rt;
    }
    // 修改角色菜单
    public static function uploadRoleMenu($list=[],$role_id="",$isadd=false){
        $DB=Database::getInstance();
        if(!$role_id){
            // ajaxReturn (404,'参数为空',$id);
            return false;
        }
        if(!is_array($list)){
            // ajaxReturn (404,'参数为空',$list);
            return false;
        }
        if(!$isadd){
            $DB->query("DELETE FROM `".DB_PREFIX."sys_role_menu` where role_id=$role_id");
        }
        foreach($list as $k => $v){
            $sql="insert into `".DB_PREFIX."sys_role_menu` (role_id,menu_id) values('$role_id','$v')";
            $DB->query($sql);
        }
        $CACHE = Cache::getInstance();
        $a=$CACHE->updateCache('menus');
        $a=$CACHE->updateCache('menuRole');
        return true;
    }
    // 获取用户列表
    public static function getMemberList($pages=[],$dt=[],$uname=""){
        $DB=Database::getInstance();
        @$isAll=$pages['isAll'];
        $output = [
			'pages'=>[
			    'isAll'=>$isAll?true:false,
    			'recordCount' => 0,     //满足条件的总记录数
    		    'pageSize' => 10,        //每页大小，即每页最多可以显示的记录数量
    		    'pageCount' => 0,       //总页数
    		    'pno' => 1,          //当前数据所在页号
			 ],
			'list' => [] ,         //当前页中的数据
	    ];
	    $bySql="ORDER BY `uid` DESC ";
	    $isfym="";$wSql="";
	    if(@$pages['pno']){
		  $output['pages']['pno'] = intval($pages['pno']);
		}
		if(@$pages['pageSize']){
		  $output['pages']['pageSize']= intval($pages['pageSize']);
		}
	    $pno = $output['pages']['pno'];$pgs =$output['pages']['pageSize'];
	    if(@$dt['name']&&@$dt['key']){
	        if($dt['name']=='uid'){
	            $wSql.=" AND ( `".$dt['name']."` = '".$dt['key']."' ) ";
	        }elseif($dt['name']=='uname'){
	            $wSql.=" AND ( `uname` LIKE '%".$dt['key']."%' OR `nickName` LIKE '%".$dt['key']."%' ) ";
	        }else{
	            $wSql.=" AND ( `".$dt['name']."` LIKE '%".$dt['key']."%' ) ";
	        }
	    }
	    if(@$dt['status']||@$dt['status']=='0'){
	        $wSql.=" AND `status`='".$dt['status']."' ";
	    }
	    if(@$dt['gender']||@$dt['gender']=='0'){
	        $wSql.=" AND `gender`='".$dt['gender']."' ";
	    }
	    if(@$dt['loginIp']){
	        $wSql.=" AND `login_ip`='".$dt['loginIp']."' ";
	    }
	    if(@$dt['orderBy']){
	        if($dt['orderBy']=="timeAsc"){
		        $bySql="ORDER BY `create_time` ASC ";
		    }
		    if($dt['orderBy']=="timeDesc"){
		        $bySql="ORDER BY `create_time` DESC ";
		    }
	    }
	    if($uname!='kingmin'){
	        $wSql.=" AND `uname`!='kingmin' ";
	    }
	    $totalSql = " SELECT COUNT(*) as total  FROM `" . DB_PREFIX . "sys_member` WHERE `isdel`='0' $wSql ;";
		$res = $DB->fetch_array($DB->query($totalSql));
		$output['pages']['recordCount'] = intval($res['total']);
		//计算总页数
		$output['pages']['pageCount'] = ceil($output['pages']['recordCount']/$output['pages']['pageSize']);
		//获取指定页中的数据
		$start = ($output['pages']['pno']-1)*$output['pages']['pageSize'];
		$count = $output['pages']['pageSize'];
		if(!$output['pages']['isAll']){
			$isfym="LIMIT $start,$count";
	    }
	    
	    $sql = "SELECT * FROM `" . DB_PREFIX . "sys_member` WHERE `isdel`='0' $wSql $bySql  $isfym;";
        $logs = $DB->query($sql);
        // $output['sql']=$sql;
        $data = array();
        foreach ($logs as $key => $v) {
            $data[]=self::memberJson($v);
        }
        $output['list']=$data;
        return $output;
    }
    // 获取用户详情
    public static function getMemberDetail($uid=""){
        $DB=Database::getInstance();
        if(!$uid){
            return false;
        }
        $sql="SELECT * FROM `".DB_PREFIX."sys_member` WHERE `uid`='$uid' ; ";
        // return $sql;
        $res =$DB->query($sql);
        $user=false;
        while($row = $DB->fetch_array($res)) {
            $user=self::memberJson($row);
        }
        return $user;
    }
    public static function getMemBerKey($name,$key="uname") {
        $DB = Database::getInstance();
        if (empty($name)) {
            return false;
        }
        $userData = false;
        if (!$userData = $DB->once_fetch_array("SELECT * FROM `".DB_PREFIX."sys_member` WHERE `$key` = '$name'")) {
            return false;
        }
        $userData=self::memberJson($userData);
        return $userData;
    }
      // 修改用户信息
    public static function uploadMemberDetail($memberData=[], $uid=""){
        $DB=Database::getInstance();
        if(!$uid){
            return false;
        }
        if(!is_array($memberData)){
            return false;
        }
        $rt=true;
        if(count($memberData)>0){
            $sql=upSqlConvert('sys_member',$memberData,"uid=$uid");
            // return $sql;
            $rt=$DB->query($sql);
            userGenxin($uid);
        }
        return $rt;
    }
        // 新增用户信息
    public static function addMemberDetail($memberData=[]){
        $DB=Database::getInstance();
        $memberKey=self::getMemBerKey(@$memberData['uname'])??true;
        if($memberKey){
            return false;
        }
        $memberData['login_ip']=getIp();
        $memberData['register_ip']=getIp();
        $memberData['login_date']=date("Y-m-d H:i:s");
        
        $sql=addSqlConvert('sys_member',$memberData);
        // return $sql;
        $rt=true;
        $rt=$DB->query($sql);
        $id=$DB->insert_id();
        
        return $id;
    }
    // 获取用户设备信息
    public static function getMemberDevices($uid){
        $DB = Database::getInstance();
        $res = $DB->query("SELECT * FROM `".DB_PREFIX."sys_member_devices` where `uid`='$uid' AND `isdel`='0' ");
        $devices['list'] = array();
        $text="";
        while($row = $DB->fetch_array($res)) {
            $row['osDt']=json_decode($row['osDt'],true);
            $devices['list'][]=$row;
            $text.=$row['model']." (".$row['system'].")"." (".$row['deviceId'].") \n\r ";
            
        }
        $devices['text']=$text;
        return $devices;
    }
    // 用户格式化
    public static function memberJson($user=false){
        if(!$user){
            return false;
        }
        unset($user['password']);
        $user['sex']=[
                "type"=>"info",
                "label"=>'未知',
            ];;
        if($user['gender']=='0'){
            $user['sex']=[
                "type"=>"",
                "label"=>"男",
            ];;
        }
        if($user['gender']=='1'){
            $user['sex']=[
                "type"=>"danger",
                "label"=>'女',
            ];;
        }
        $user['name']=$user['uname'];
        if($user['nickName']){
            $user['name']=$user['nickName'];
        }
        $user['avatar']=imgUrlpd($user['avatar']?$user['avatar']:'/content/images/icon/default.jpg');
        $user['photo']=imgUrlpd($user['avatar']?$user['avatar']:'/content/images/icon/default.jpg');
        if($user['status']=='0'){
            $tag=[
                "type"=>"success",
                "label"=>"正常",
            ];
            if(!isUserOnLine($user['uid'])){
                $tag["type"]="info";
            }
        }else{
            $tag=[
                "type"=>"danger",
                "label"=>"停用",
            ];
        }
        $user['statusTag']=$tag;
        $devices=self::getMemberDevices($user['uid']);
        $user['devices']= $devices['list'];
        $user['device']= $devices['text'];
        return $user;
    }
    
    // 新增web登录状态
    public static function webBindUser($dt=[]){
        $userLogin="";$password="";$log_status=1;$msg="登录聊天成功";$bz="";
        $DB = Database::getInstance();
        @$uid=$dt['uid']??'';
        if(!$uid){
            return false;
        }
        @$status=$dt['formType']??'';
        @$osDt="";
        @$log_ip=getIp();
        @$location =ipToArea($log_ip);
        if($status!='admin'){
            @$log_os=$dt['os']['model'].'('.$dt['os']['system'].')';
            @$log_browser=$dt['os']['hostName'].'('.$dt['os']['hostVersion'].')';
            @$osDt=json_encode($dt['os'],JSON_UNESCAPED_UNICODE);
        }else{
            $log_browser=get_broswer();
            $log_os=get_os();
        }
        $sql="INSERT INTO `".DB_PREFIX."sys_log_login`(`status`,`uid`,`user_name`, `user_password`, `log_ip`,`location`, `log_browser`, `log_os`,`osDt`, `log_status`, `log_msg`,`remark`) VALUES('$status','$uid','$userLogin','$password','$log_ip','$location','$log_browser','$log_os','$osDt','$log_status','$msg','$bz')";
        // return $sql;
        $DB->query($sql);
    }
    /////////////////////////////////////////////////////////////////////
 
}
